<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\library\wechat\Wechatjssdk;
use app\api\library\wechat\WXBizMsgCrypt;
use think\Log;
use think\Db;

/**
 * 微信小店回调
 */
class Wechatstore extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    private  $token = "a68a5df7365747268f382745692e043d";
    private  $EncodingAESKey = "FHUFHge0tOZvucfLgTgKXJJmkqf3FwZZ6FZ0OoCS3Xk";
    private  $appid="wx0d138e558b650d4f";
    private  $appSecret="587b3501126e4eaf63eed7974d03a36d";
    private  $nonce =null;
    private  $timestamp =null;
    private  $signature =null;
    private  $echostr =null;
    private  $msg_signature =null;


    public function _initialize()
    {
        parent::_initialize();
        $this->signature();
    }
    


    
    private  function signature(){
            $this->signature = $this->request->param('signature','');
            $this->nonce = $this->request->param('nonce','');
            $this->echostr = $this->request->param('echostr','');
            $this->timestamp = $this->request->param('timestamp','');
            $this->msgSignature = $this->request->param('msg_signature','');
        
        if($this->request->isGet()){
            $data=[];
            $data['token'] =$this->token;
            $data['timestamp'] = $this->timestamp;
            $data['nonce'] = $this->nonce;
            sort($data);
            $str = implode('', $data);
            $sign = sha1($str);
            if($sign==$this->signature){
                exit($this->echostr);
            } 
        }
        
    }

    /**
     * 订单回调
     *
     */
    public function orderCallback()
    {
        $data = file_get_contents("php://input");
        $url = $this->request->get();
        file_put_contents("../runtime/orderData.txt", 'param=='.json_encode($url)."\r\n",FILE_APPEND);
        file_put_contents("../runtime/orderData.txt", $data."\r\n",FILE_APPEND);
        $this->decodeOrder();
        
//        $wsdk = new Wechatjssdk($this->appid, $this->appSecret);
//        echo $wsdk->getAccessToken();
//        $this->success('请求成功');
    }
    public function orderCallback2()
    {
        $wsdk = new Wechatjssdk($this->appid, $this->appSecret);
        echo $wsdk->getAccessToken();
//        $this->success('请求成功');
    }
    
    
    /*
     * 解密数据
     */
    public function decodeOrder() {
        $data = file_get_contents("php://input");
        $data = json_decode($data,TRUE);
        $pc = new WXBizMsgCrypt($this->token, $this->EncodingAESKey, $this->appid);
//        $post =<<<PP
//{"ToUserName":"gh_6d7b8f0733ba","Encrypt":"gi79/ytFX+Nb0dW4p54/QFtvCfT4DUbrBu21PWZcF3kEmohrjT7bHZE/opBhdVDNoOPqUM68oXbmivUQRUXMfs4rBhbEkzvM3ZYj9t+t5PElbOH+2W6/OIdcz097Ru23xrpFkvk/UMZoZ9nJay3qkyYW4x4p9W/fjpdWHfj4KjOqT1CdfbN4XrxyynWE/KWmjwtA4jxu2CSytb7jakzxMFVWcyRMVm3qeJyFHDpuKSHzbD49hDuSrk3p47zGtoHhdjgORG0+ptOGjgpD4z31esTvcJUVk7v6P/l8r9j52TdldYW3zAOzcZE+4e/uFmZSH0UZ3m4T8QgmPyDUnYuhFA=="}
//PP;
        $post = $this->request->post();
        $post = json_encode($post);
        // 第三方收到公众号平台发送的消息
        $msg = '';
        $errCode = $pc->decryptMsg($this->msgSignature, $this->timestamp, $this->nonce, $post, $msg);
        if ($errCode == 0) {
//                print("解密后: " . $msg . "\n");
                $msgObj = json_decode($msg, $msg);
                $this->saveLog("succat",$msgObj);
                if($msgObj['MsgType']=="event"){
//                    var_dump($msgObj['Event']);
                    switch ($msgObj['Event']) {
                        case "channels_ec_order_pay": //支付
                            $orderId = $msgObj['order_info']["order_id"];
                            $param =[];
                            $param['appid'] = $msgObj['ToUserName'];
                            $param['openid'] = $msgObj['FromUserName'];
                            $param['order_event'] = $msgObj['Event'];
                            $param['order_id'] = $orderId;
                            $param['order_createtime'] = $msgObj['CreateTime'];
                            $param['status'] = 1;
                            self::saveOrder($orderId, $param);
                            break;
                        case "channels_ec_order_cancel": //订单取消
                            $orderId = $msgObj['order_info']["order_id"];
                            $param =[];
                            $param['status'] = 0;
                            $param['order_event'] = $msgObj['Event'];
                            self::saveOrder($orderId, $param);
                            break;
                        case "channels_ec_aftersale_update": //订单售后提交
                             $finderOrder = $msgObj['finder_shop_aftersale_status_update'];
                             $orderId = $finderOrder["order_id"];
                            if($finderOrder['status'] =='USER_CANCELD'){
                                $param['status'] = 1;
                            }else{
                                $param['status'] = 0;
                            }
                            $param['order_event'] = $msgObj['Event'];
                            self::saveOrder($orderId, $param);
                            break;

                        default:
                            break;
                    }
                    
                }
//                $encryptMsg="";
                $replyDara =[];
//                $rsp = $pc->encryptMsg("{}", $timeStamp, $nonce, $encryptMsg);
//                var_dump($encryptMsg);
                $post = json_decode($post, 1);
                $replyDara['Encrypt'] =$post['Encrypt'];
                $replyDara['MsgSignature'] =$this->msgSignature;
                $replyDara['TimeStamp'] =$this->timestamp;
                $replyDara['Nonce'] =$this->nonce;
                exit(json_encode($replyDara));
        } else {
            $this->saveLog("err");
        }
        
    }
    
    /*
     * 记录日志log
     */
    private  function saveLog($type="succat",$data=[]) {
        $getPdata = $this->request->get();
        $postPdata = $this->request->post();
        
        file_put_contents("../runtime/log/order_{$type}_log".date('Ymd').'.text', date("Y-m-d H:i:s").json_encode($getPdata).PHP_EOL.json_encode($postPdata).PHP_EOL.json_encode($data) .PHP_EOL,FILE_APPEND);
    }
    
    /*
     * 保存或者更新订单
     */
    private static function saveOrder($orderId,$param) {
        $order = Db::name("wechat_orders")->where(["order_id"=>$orderId])->find();
        $param['updatetime'] = time();
        if(empty($order)){
            $param['createtime'] = time();
            return  Db::name("wechat_orders")->insert($param);
        } else {
            if(empty($param['status'])){
                self::closeOrder($order);
            }
            return  Db::name("wechat_orders")->where(["order_id"=>$orderId])->update($param);
        }
    }
    
    /*
     * 设置任务为退货补单
     */
    private static function closeOrder($order){
        
        if($order['is_used']==1 && $order['task_id']>0){
            $task = Db::name("expert_upgrade_order")->where(['id'=>$order['task_id']])->find();
            if(empty($task)){
                //查询所有同级任务是否已经全部完成
                $count = Db::name("expert_upgrade_order")->where(['user_id'=>$order['user_id'],'upgrade_type'=>$order['upgrade_type'],"status"=>["in",[0,1,-1,-2]]])->count();
                if($count>0){
                    //存在其他未完成任务，
                    $row = Db::name("expert_upgrade_order")->where(['id'=>$order['task_id']])->update(["status"=>"-2"]);
                }else{
                    //全部完成的任务；可能已经升级了；要隐藏掉
                    $row = Db::name("expert_upgrade_order")->where(['id'=>$order['task_id']])->update(["status"=>"-2"]);
                    //设置隐藏
                    Db::name("expert_relation")->where(["user_id"=>$order['user_id']])->update(["status"=>0]);                    
                }                
            }            
        }
    }
    
}
